package problem152;

//153.乘积最大子数组
//https://leetcode.cn/problems/maximum-product-subarray/

class Solution {
    public int maxProduct(int[] nums) {
        int n = nums.length;
        if(n == 1) return nums[0];
        int[] f = new int[n+1];
        int[] g = new int[n+1];
        int ret = Integer.MIN_VALUE;
        for(int i = 1; i<=n; i++) {
            if(nums[i-1] >= 0) {
                f[i] = Math.max(f[i-1]*nums[i-1], nums[i-1]);
                g[i] = Math.min(g[i-1]*nums[i-1], nums[i-1]);
            }else {
                f[i] = Math.max(g[i-1]*nums[i-1], nums[i-1]);
                g[i] = Math.min(f[i-1]*nums[i-1], nums[i-1]); 
            }
            ret = Math.max(ret, f[i]);
            System.out.println(f[i] + " " + g[i]);
        }
        return ret;
    }
}

/*
f[i]: 以第i个元素为结尾, 乘积为正数的最小值
g[i]: 以第i个元素为结尾, 乘积为负数的最小值
nums[i] >= 0 :
f[i] = Math.max(f[i-1]*nums[i], nums[i]);
g[i] = Math.min(g[i-1]*nums[i], nums[i]);
nums[i] < 0:
f[i] = Math.max(g[i-1]*nums[i], nums[i]);
g[i] = Math.min(f[i-1]*nums[i], nums[i]); 
*/